package bean;

import java.sql.*;

public class DB {
	private final String classname = "com.mysql.cj.jdbc.Driver"; // 更新的驱动类
	private final String url = "jdbc:mysql://localhost:3306/student?serverTimezone=GMT"; // 加入时区
	private final String user = "root";
	private final String pwd = "123456";

	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;

	public DB() {
		try {
			Class.forName(classname); // 不需要 newInstance
		} catch (ClassNotFoundException e) {
			System.err.println("加载数据库驱动失败：" + e.getMessage());
			e.printStackTrace();
		}
	}

	public Connection createConn() {
		try {
			conn = DriverManager.getConnection(url, user, pwd);
		} catch (SQLException e) {
			System.err.println("获取数据库连接失败：" + e.getMessage());
			e.printStackTrace();
		}
		return conn;
	}

	public Statement getStmt() {
		createConn();
		try {
			if (conn != null) {
				stmt = conn.createStatement();
			}
		} catch (SQLException e) {
			System.err.println("创建 Statement 对象失败：" + e.getMessage());
			e.printStackTrace();
		}
		return stmt;
	}

	public boolean executeUpdate(String sql) {
		boolean mark = false;
		try (Connection connection = createConn();
			 Statement statement = connection.createStatement()) {
			int iCount = statement.executeUpdate(sql);
			mark = iCount > 0;
		} catch (SQLException e) {
			System.err.println("执行更新失败：" + e.getMessage());
			e.printStackTrace();
		}
		return mark;
	}

	public ResultSet executeQuery(String sql, String... params) {
		try {
			getStmt();
			if (stmt != null) {
				// 使用 PreparedStatement 执行查询，传入参数
				PreparedStatement ps = conn.prepareStatement(sql);
				for (int i = 0; i < params.length; i++) {
					ps.setString(i + 1, params[i]); // 将参数设置到 SQL 查询中
				}
				rs = ps.executeQuery();
			}
		} catch (SQLException e) {
			System.err.println("查询数据库失败：" + e.getMessage());
			e.printStackTrace();
		}
		return rs;
	}


	public void close() {
		try {
			if (rs != null) rs.close();
		} catch (SQLException e) {
			System.err.println("关闭 ResultSet 失败：" + e.getMessage());
		}
		try {
			if (stmt != null) stmt.close();
		} catch (SQLException e) {
			System.err.println("关闭 Statement 失败：" + e.getMessage());
		}
		try {
			if (conn != null) conn.close();
		} catch (SQLException e) {
			System.err.println("关闭 Connection 失败：" + e.getMessage());
		}
	}
}
